from django.shortcuts import render

# Create your views here.
from rest_framework import status, mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, GenericAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from user import constants, serializers
from user.models import User

# POST /users/
from user.serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer


class UserView(GenericAPIView):
    # 指定视图所使用的序列化器类
    serializer_class = CreateUserSerializer

    def post(self, request):
        """
        注册用户信息的保存：
        1. 获取信息并进行校验
        2. 创建新用户并保存到数据库
        3. 返回应答， 注册成功
        """
        # 1.获取信息并进行校验
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 2.创建新用户并保存到数据库
        serializer.save()
        # 3.返回应答， 注册成功
        return Response(serializer.data, status=status.HTTP_201_CREATED)


class UsernameCountView(APIView):
    """用户名数量"""

    def get(self, request, username):
        """
        获取指定用户名数量，并返回
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


class MobileCountView(APIView):
    """手机号数量"""

    def get(self, request, mobile):
        """获取指定手机号数量"""
        count = User.objects.filter(mobile=mobile).count()

        data = {
            "mobile": mobile,
            "count": count
        }
        return Response(data)


# class UserView(CreateAPIView):
#     """
#     用户注册
#     """
#
#     serializer_class = serializers.UserSerializer
class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = UserDetailSerializer
    # 从数据库获取用户信息，进行序列化然后返回

    # 给当前视图添加权限: 仅通过认证的用户能够访问该视图
    permission_classes = [IsAuthenticated]

    def get_object(self):
        # 我们通过 self.request.user 能够直接拿到通过 token 传过来的对象
        return self.request.user


class EmailView(UpdateAPIView):
    """保存邮箱并发送邮件"""
    # 设置当前视图的访问权限（只有认证过的用户才能进行访问）
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        """返回登录用户对象"""
        return self.request.user


# PUT /emails/verification/?token=<加密用户信息>
class EmailVerifyView(APIView):
    def put(self, request):
        """
        用户邮箱验证：
        1. 获取token并校验
        2. 设置对应用户邮箱的email_active标记为true
        3. 返回应答，验证成功
        """

        # 1. 获取token并校验（token必传，token解密是否有效）
        token = request.query_params.get("token")  # None

        if token is None:
            return Response({"message": "缺少token参数"}, status=status.HTTP_400_BAD_REQUEST)

        # token解密是否有效
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '无效的token数据'}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 设置对应用户邮箱的email_active标记为True
        user.email_active = True
        user.save()

        # 3. 返回应答，验证成功
        return Response({'message': 'OK'})


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)
